package com.joke.model;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;

public class Constants {

	public static List<Story> gStoryList = null;
	
	/** update jokeInfo* */
	public static int update() {
		
		int returnCode = 1;
		String line = null;
		BufferedReader buffer = null;
		HttpURLConnection urlConn = null;
		StringBuffer sb = new StringBuffer();
		gStoryList = new ArrayList<Story>();
		
		String urlStr = "http://androidside.jeecms.com/jeeadmin/jeecms/androidapp/v_list.do?path=joke&unicode=UTF-8";
		try {
			URL url = new URL(urlStr);
			urlConn = (HttpURLConnection) url.openConnection();

			urlConn.setRequestProperty("User-Agent", "Mozilla/5.0");
			urlConn.setConnectTimeout(3 * 1000);

			if (urlConn.getResponseCode() == 200) {
				
				buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
				while ((line = buffer.readLine()) != null) {
					sb.append(line);
				}
				
				JSONObject jsonObject = new JSONObject(sb.toString());
				JSONArray resultlist = jsonObject.getJSONArray("resultlist");
				
				if(resultlist != null){
					int len = resultlist.length();
					for (int i = 0; i < len; i++) {
						Story joke = new Story();
						JSONObject story = resultlist.getJSONObject(i);
						joke.setTitle(story.getString("title"));
						joke.setContent(filterString(story.getString("content")));
						gStoryList.add(joke);
					}
				}
			}else{
				//不能连接服务器
				returnCode = 1;
			}
			
			//获取列表成功
			if(gStoryList.size() > 0)
				returnCode = 200;
			
		} catch (Exception e) {
			e.printStackTrace();
			//获取列表异常
			returnCode = -1;
		} finally {
			try {
				if (buffer != null)
					buffer.close();
				if (urlConn != null)
					urlConn.disconnect();
			} catch (Exception e) {
				e.printStackTrace();
				//获取列表异常
				returnCode = -1;
			}
		}
		return returnCode;
	}
    
	/**filter html text**/
	public static String filterString(String input) {   
        if (input == null || input.trim().equals("")) {   
            return "";   
        }   
          
        String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll("<[^>]*>", "");   
        str = str.replaceAll("[(/>)<]", "");   
        int len = str.length(); 
        int milen = input.length();
        if (len <= milen) {   
            return str;   
        } else {   
            str = str.substring(0, milen);   
        }   
        return str;   
	}
}
